from nmj.sqlite.nmj_db import NMJ_MOVIE_TYPE
from nmj.tools.helpers import download_image
from urllib2 import HTTPError
import Image
import logging
import os
import re

_LOGGER = logging.getLogger(__name__)

NMJ_THUMB_SIZE = (246, 370)

def resize_image(filename, new_size, new_filename=None):
	if not os.path.isfile(filename):
		return
	original = Image.open(filename)
	resized = original.resize(new_size, Image.BICUBIC)
	if new_filename:
		resized.save(new_filename)
	else:
		resized.save(filename)

class LocalNMJImage(object):
	def __init__(self, path, thumbnail_path=None):
		self.path = path
		self.thumbnail_path = thumbnail_path

	def get_thumbnail(self, filepath):
		pass

	def get_image(self, filepath):
		pass

class NMJImage(object):
	def __init__(self, url, thumbnail_url=None):
		_LOGGER.debug("Create new NMJImage(url=%s, thumbnail_url=%s)", url, thumbnail_url)
		self.url = url
		self.thumbnail_url = thumbnail_url
		self.filename = os.path.basename(self.url)
		if self.thumbnail_url:
			self.thumbname = os.path.basename(self.thumbnail_url)
		else:
			name, ext = os.path.splitext(self.filename)
			self.thumbname = "%s_thumb%s" % (name, ext)
		_LOGGER.debug("Image thumbname is %s", self.thumbname)
		self.filepath = ""
		self.thumbpath = ""

	def __str__(self):
		return "NMJImage(%s)" % self.url

	def get_thumbnail(self, directory):
		self.thumbpath = os.path.join(directory, self.thumbname)
		if self.thumbnail_url:
			_LOGGER.debug("Download thumbname is %s", self.thumbname)
			download_image(self.thumbnail_url, self.thumbpath)
			resize_image(self.thumbpath, NMJ_THUMB_SIZE)
		else:
			_LOGGER.debug("Download thumbname is %s", self.thumbname)
			self.get_image(directory)
			resize_image(self.filepath, NMJ_THUMB_SIZE, new_filename=self.thumbpath)
		return self.thumbpath

	def get_image(self, directory):
		self.filepath = os.path.join(directory, self.filename)
		if self.url:
			download_image(self.url, self.filepath)
		return self.filepath

class NMJMovie(object):
	def __init__(self, title,
			synopsis="", short_synopsis="", posters=None, fanarts=None,
			genres=None, cast=None, show_type=NMJ_MOVIE_TYPE, rating=0.0):
		self.title = title
		self.sortable_title = re.sub('(le|la|un|une)(\s+)', '\2', title).strip()
		self.synopsis = synopsis
		self.short_synopsis = short_synopsis
		self.posters = posters or []
		self.fanarts = fanarts or []
		self.empty = NMJImage("", "")
		if self.posters:
			self.poster = self.posters[0]
		else:
			self.poster = self.empty
		if self.fanarts:
			self.fanart = self.fanarts[0]
		else:
			self.fanart = self.empty
		self.genres = genres
		self.cast = cast
		self.rating = rating
		self.show_type = show_type

	def __cmp__(self, other):
		if self.sortable_title < other.sortable_title:
			return -1
		elif self.sortable_title > other.sortable_title:
			return 1
		return 0

	def update_attr(self, **kwargs):
		for attr, value in kwargs.items():
			setattr(self, attr, value)

	def get_poster(self, directory, index=None):
		index = index or 0
		for poster in self.posters[index:]:
			try:
				poster.get_image(directory)
				poster.get_thumbnail(directory)
				self.poster = poster
				return
			except HTTPError:
				_LOGGER.exception("Cannot download poster image %s", poster)

	def get_fanart(self, directory, index=None):
		index = index or 0
		for fanart in self.fanarts[index:]:
			try:
				fanart.get_image(directory)
				self.fanart = fanart
				return
			except HTTPError:
				_LOGGER.exception("Cannot download fanart image %s", fanart)

	def __str__(self):
		return "<TMDBMovie = title:%s,fanart=%s,poster=%s>" % (self.title, self.fanart, self.poster)


